/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-5-13 下午2:56 Created by dwzhang
 */
package com.jade.bss.web.controller;

import java.util.Date;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jade.bss.base.RoleAction;
import com.jade.bss.base.customer.Customer;
import com.jade.bss.base.customer.CustomerManager;
import com.jade.bss.base.provision.ProvisionService;
import com.jade.bss.base.provision.customer.CustomerContext;
import com.jade.bss.base.utils.CopyBean;
import com.jade.bss.web.vo.CustomerVo;
import com.jade.framework.base.context.ApplicationContextUtils;
import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.CriterionUtils;
import com.jade.framework.base.criterion.MatchMode;
import com.jade.framework.base.criterion.Restrictions;
import com.jade.framework.base.util.PagingList;
import com.jade.framework.base.util.PagingResult;
import com.jade.framework.base.util.ResponseUtils;
import com.jade.modules.region.RegionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

/**
 * 客户控制器。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a>
 * @version 1.0 15-5-13 下午2:56
 */
@RestController
@RequestMapping (value = "/customer")
@Api(value = "用户账号", description = "用户账号")
public class CustomerController
{
    private CustomerManager customerManager = ApplicationContextUtils.getBean("bss_customerManager");
    private ProvisionService provisionService = ApplicationContextUtils.getBean("bss_provisionService");

    @RequiresAuthentication
    //@RequiresPermissions (value = {"customer:view"})
    @RequestMapping (value = RoleAction.QUERY, method = RequestMethod.GET)
    @ApiOperation(value = "查询用户", httpMethod = "GET", response = Customer.class)
    public void query(@ApiParam(value = "地区标识") @RequestParam (value = "regionId", required = false) String regionId,
                      @ApiParam(value = "状态") @RequestParam (value = "status", defaultValue = "-1") int status,
                      @ApiParam(value = "关键词") @RequestParam (value = "keyword", required = false) String keyword,
                      @ApiParam(value = "起始值") @RequestParam (value = "offset", defaultValue = "0") int offset,
                      @ApiParam(value = "每页大小") @RequestParam (value = "length", defaultValue = "10") int length,
                      @ApiParam(value = "排序字段") @RequestParam (value = "sort", required = false) String sort,
                      @ApiParam(value = "排序规则", allowableValues = "desc, asc") @RequestParam (value = "order", required = false) String order,
                      @ApiParam(value = "传递信息") @RequestParam (value = "callback", required = false) String callback, HttpServletResponse response)
            throws Exception
    {
        Criteria criteria = new Criteria(offset, length);
        if (status > 0) {
            criteria.add(Restrictions.eq("status", status));
        }
        if (StringUtils.isNotBlank(regionId)) {
            criteria.add(Restrictions.or(Restrictions.eq("country", regionId), Restrictions.eq("province", regionId),
                    Restrictions.eq("city", regionId), Restrictions.eq("county", regionId)));
        }
        if (StringUtils.isNotBlank(keyword)) {
            criteria.add(Restrictions.or(Restrictions.like("customer", "name", keyword, MatchMode.ANYWHERE),
                    Restrictions.like("customer", "trueName", keyword, MatchMode.ANYWHERE)));
        }
        CriterionUtils.addOrder(criteria, sort, order, "creationDate");
        PagingList<Customer> customers = customerManager.queryCustomer(criteria);

        PagingResult result = PagingResult.getResult(customers);
        result.setCallback(callback);
        if (!customers.isEmpty()) {
            HashMap<Long, String> regionInfo = new HashMap<Long, String>();
            for (Customer customer : customers) {
                if (StringUtils.isNotBlank(customer.getProvince()) && StringUtils.isNotBlank(customer.getCity())) {
                    regionInfo.put(customer.getId(),
                            RegionUtils.getName(customer.getProvince(), true) + "-" + RegionUtils.getName(
                                    customer.getCity(), true));
                }
            }
//            result.setParam("regionInfo", regionInfo);
        }
        result.setOffset(offset);
        result.setPageSize(length);
        ResponseUtils.writeSuccessPagingResult(response, result);
    }
    @RequiresAuthentication
    //@RequiresPermissions (value = {"customer:add"})
    @RequestMapping (value = RoleAction.ADD, method = RequestMethod.POST)
    @ApiOperation(value = "增加用户", httpMethod = "POST")
    public void add(@ApiParam(value = "用户对象") @RequestBody CustomerVo customerVo, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        CustomerContext customerContext = new CustomerContext(CustomerContext.TYPE_REGISTER_CUSTOMER);
        Customer customer = CopyBean.copy(customerVo, Customer.class);
        customer.setType(Customer.DEFAULT_TYPE);
        customer.setCreationDate(new Date());
        customerContext.setCustomer(customer);
        provisionService.provision(customerContext);
        ResponseUtils.writeSuccessResult(response, customer);
    }

    @RequiresAuthentication
    //@RequiresPermissions (value = {"customer:edit"})
    @RequestMapping (value =  RoleAction.UPDATE, method = RequestMethod.PUT)
    @ApiOperation(value = "编辑用户", httpMethod = "PUT")
    public void update(@ApiParam(value = "用户对象") @RequestBody CustomerVo customerVo, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    { 
        Customer customer = CopyBean.copy(customerVo, Customer.class);
        customerManager.updateCustomer(customer);
        ResponseUtils.writeSuccessResult(response);
    } 
    
   @RequiresAuthentication
    //@RequiresPermissions (value = {"customer:remove"})
    @RequestMapping (value =RoleAction.DELETE, method = RequestMethod.DELETE)
    @ApiOperation(value = "删除用户", httpMethod = "DELETE")
    public void remove(@ApiParam(value = "用户标识") @PathVariable ("id") long[] ids, HttpServletResponse response)
            throws Exception
    {
        for (long id : ids) {
            CustomerContext customerContext = new CustomerContext(CustomerContext.TYPE_DEREGISTER_CUSTOMER);
            customerContext.setCustomerId(id);
            provisionService.provision(customerContext);
        }
        ResponseUtils.writeSuccessResult(response);
    }

   @RequiresAuthentication
    @RequestMapping (value = RoleAction.GET, method = RequestMethod.GET)
    @ApiOperation(value = "获取指定用户", httpMethod = "GET")
    public void get(@ApiParam(value = "用户标识") @PathVariable long id, HttpServletResponse response)
            throws Exception
    {
        Customer customer = customerManager.getCustomer(id);
        ResponseUtils.writeSuccessResult(response, customer);
    }
    @RequiresAuthentication
    //@RequiresPermissions (value = {"customer:remove"})
    @RequestMapping (value =RoleAction.DISABLED, method = RequestMethod.DELETE)
    @ApiOperation(value = "停用账号", httpMethod = "DELETE")
    public void DISABLED(@ApiParam(value = "用户标识") @PathVariable ("id") long[] ids, HttpServletResponse response)
            throws Exception
    {
        for (long id : ids) {
            CustomerContext customerContext = new CustomerContext(CustomerContext.TYPE_DEREGISTER_CUSTOMER);
            customerContext.setCustomerId(id);
            provisionService.provision(customerContext);
        }
        ResponseUtils.writeSuccessResult(response);
    }
    @RequiresAuthentication
    //@RequiresPermissions (value = {"customer:remove"})
    @RequestMapping (value ="resetPassword", method = RequestMethod.GET)
    @ApiOperation(value = "密码重置", httpMethod = "GET")
    public void resetPassword(@ApiParam(value = "用户标识") @RequestParam (value = "id") long id, @RequestParam (value = "password") String password, HttpServletResponse response)
            throws Exception
    {
        customerManager.resetPassword(id,password);
        ResponseUtils.writeSuccessResult(response);
    }
    @RequiresAuthentication
    //@RequiresPermissions (value = {"customer:remove"})
    @RequestMapping (value ="mdps", method = RequestMethod.GET)
    @ApiOperation(value = "修改密码", httpMethod = "GET")
    public void mdps(@ApiParam(value = "用户标识") @RequestParam (value = "id") long id, @RequestParam (value = "oldps") String oldps,
                         @RequestParam (value = "newps") String newps,HttpServletResponse response)
            throws Exception
    {
        customerManager.modifyPassword(id,oldps,newps);
        ResponseUtils.writeSuccessResult(response);
    }
}
